/**
 * Created by yindume on 2018/12/10.
 */
var express = require('express');
var router = express.Router();
var db = require('../../../libs/mysql');
//统一返回格式
var res_Data;
router.use( function(req, res, next) {
    res_Data = {
        code: 0,
        message: ''
    }
    next();
});
router.get('/',function (req,res) {
    var page = 1; //默认为1
    var num = 10; //一页条数
    if (req.query.page) {
        page = parseInt(req.query.page);
    }
    var count = 0;
    var pages = 0;
    db.query(`select count(*) from contents;`,(err,count)=>{
        if(err){
            res.send('内容总条数').end();
        }else {
            count = count[0]['count(*)'];
            pages = Math.ceil(count/num);//总页数

            var sql = 'SELECT u.nickname,c.`name`,t.* FROM contents t LEFT JOIN `user` u ON t.userid = u.id LEFT JOIN category c ON t.categoryid = c.id order by id desc limit ' + num + ' offset ' + num * (page - 1);

            db.query(sql,(err,data)=>{
                if(err){
                    res.send('内容列表查询').end();
                }else {
                    res.render('admin/content/content', {
                        userInfo:req.userInfo,
                        contents:data,
                        count:count,
                        pages:pages,
                        page: page,
                        num:num
                    });
                }
            })
        }
    })
});

router.use('/add',require('./add'));//添加
router.use('/edit',require('./edit'));//修改
router.use('/del',function(req,res){//删除
    var id = req.query.id;
    db.query(`delete from contents where id = '${id}';`,(err,data) => {
        if(err){
            res.send('内容删除').end();
        }else {
            res.redirect('/admin/content');
        }
    })
});


module.exports = router;